<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <a-page-header title="用户管理" sub-title="管理系统用户信息" />

    <!-- 工具栏 -->
    <a-card class="toolbar-card">
      <a-row :gutter="16">
        <a-col :span="18">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon><PlusOutlined /></template>
              新增用户
            </a-button>
            <a-button
              danger
              :disabled="!hasSelected"
              @click="handleBatchDelete"
            >
              <template #icon><DeleteOutlined /></template>
              批量删除
            </a-button>
            <a-button @click="handleRefresh">
              <template #icon><ReloadOutlined /></template>
              刷新
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="6">
          <a-input-search
            v-model:value="queryParams.keyword"
            placeholder="搜索用户名或邮箱"
            allow-clear
            @search="handleSearch"
          />
        </a-col>
      </a-row>

      <!-- 筛选条件 -->
      <a-row :gutter="16" style="margin-top: 16px">
        <a-col :span="6">
          <a-select
            v-model:value="queryParams.role"
            placeholder="请选择角色"
            allow-clear
            style="width: 100%"
            :options="ROLE_OPTIONS"
            @change="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-select
            v-model:value="queryParams.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 100%"
            :options="STATUS_OPTIONS"
            @change="handleSearch"
          />
        </a-col>
      </a-row>
    </a-card>

    <!-- 用户列表表格 -->
    <a-card class="table-card">
      <CommonTable
        :columns="TABLE_COLUMNS"
        :data-source="list"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #status="{ text, record }">
          <a-tag :color="text === 'active' ? 'success' : 'default'">
            {{ text === 'active' ? '启用' : '禁用' }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <a-space>
            <a-button type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个用户吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </CommonTable>
    </a-card>

    <!-- 新增/编辑用户弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :width="600"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <CommonForm
        ref="formRef"
        :fields="formFields"
        :initial-values="formData"
        :show-footer="false"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import type { User } from '@/types'
import CommonTable from '@/components/CommonTable/index.vue'
import CommonForm from '@/components/CommonForm/index.vue'
import { TABLE_COLUMNS, FORM_FIELDS, ROLE_OPTIONS, STATUS_OPTIONS } from './components/config'
import { Modal, message } from 'ant-design-vue'
import {
  PlusOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const { list, loading, pagination, queryParams } = storeToRefs(userStore)

// 表单引用
const formRef = ref()

// 弹窗相关
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const currentUser = ref<User | null>(null)

// 表单数据
const formData = ref<Record<string, any>>({})

// 选中的行
const selectedRowKeys = ref<number[]>([])

// 弹窗标题
const modalTitle = computed(() => {
  return modalType.value === 'add' ? '新增用户' : '编辑用户'
})

// 是否有选中项
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 表单字段配置（编辑时密码非必填）
const formFields = computed(() => {
  if (modalType.value === 'edit') {
    return FORM_FIELDS.map(field => {
      if (field.name === 'password') {
        return { ...field, required: false }
      }
      return field
    })
  }
  return FORM_FIELDS.map(field => {
    if (field.name === 'password') {
      return { ...field, required: true, rules: [
        { required: true, message: '请输入密码' },
        { min: 6, message: '密码长度不少于 6 位' }
      ]}
    }
    return field
  })
})

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys
  },
  getCheckboxProps: (record: User) => ({
    disabled: record.username === 'admin', // 禁止选中 admin 用户
  }),
}))

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})

/**
 * 加载数据
 */
async function loadData() {
  await userStore.fetchUserList()
}

/**
 * 搜索
 */
function handleSearch() {
  queryParams.value.page = 1
  loadData()
}

/**
 * 表格变化回调
 */
function handleTableChange(paginationConfig: any, filters: any, sorter: any) {
  // 更新分页参数
  queryParams.value.page = paginationConfig.current
  queryParams.value.pageSize = paginationConfig.pageSize

  // 更新排序参数
  if (sorter.field) {
    queryParams.value.sortField = sorter.field
    queryParams.value.sortOrder = sorter.order
  } else {
    queryParams.value.sortField = undefined
    queryParams.value.sortOrder = undefined
  }

  loadData()
}

/**
 * 刷新
 */
function handleRefresh() {
  selectedRowKeys.value = []
  loadData()
}

/**
 * 新增用户
 */
function handleAdd() {
  modalType.value = 'add'
  currentUser.value = null
  formData.value = {}
  modalVisible.value = true
}

/**
 * 编辑用户
 */
function handleEdit(user: User) {
  modalType.value = 'edit'
  currentUser.value = user
  formData.value = { ...user }
  // 编辑时不显示密码
  delete formData.value.password
  modalVisible.value = true
}

/**
 * 删除用户
 */
async function handleDelete(id: number) {
  await userStore.deleteUserItem(id)
  selectedRowKeys.value = selectedRowKeys.value.filter(key => key !== id)
}

/**
 * 批量删除
 */
function handleBatchDelete() {
  if (!hasSelected.value) {
    message.warning('请先选择要删除的用户')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个用户吗？`,
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      await userStore.batchDeleteUserItems(selectedRowKeys.value)
      selectedRowKeys.value = []
    },
  })
}

/**
 * 弹窗确定
 */
async function handleModalOk() {
  try {
    modalLoading.value = true

    // 验证表单
    const values = await formRef.value.validate()

    // 提交数据
    let success = false
    if (modalType.value === 'add') {
      success = await userStore.addUserItem(values)
    } else {
      success = await userStore.updateUserItem(currentUser.value!.id, values)
    }

    if (success) {
      modalVisible.value = false
      formData.value = {}
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    modalLoading.value = false
  }
}

/**
 * 弹窗取消
 */
function handleModalCancel() {
  modalVisible.value = false
  formData.value = {}
}
</script>

<style scoped lang="less">
.user-management {
  .toolbar-card {
    margin-bottom: 16px;
  }

  .table-card {
    :deep(.ant-card-body) {
      padding: 24px;
    }
  }
}
</style>
